import React, { useEffect } from 'react'
import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons'
import { Button, Dropdown, Tooltip } from 'antd'
import type { MenuProps } from 'antd'
import { useUserStore } from '@/store/user'
import { useAppStore } from '@/store/app'
import { useNavigate } from 'react-router-dom'
import styles from './index.module.less'
import avaterIcon from '@/assets/avatar.gif'
import TopBar from '@/components/TopBar'
import BreadCrumb from '../BreadCrumb'
import SunnyIcon from '@/assets/icons/svg/sunny.svg'
import MoonIcon from '@/assets/icons/svg/moon.svg'

const NavHeader: React.FC = () => {
  const navigate = useNavigate()
  const { userInfo, logout } = useUserStore(state => state)
  const { collapsed, layout, theme, updateTheme, updateCollapsed } = useAppStore(state => state)

  useEffect(() => {
    initTheme()
  }, [])

  /**
   * 主题样式
   */
  const dropdownItems: MenuProps['items'] = [
    {
      key: '1',
      label: <span>个人中心</span>
    },
    {
      key: '2',
      label: <span>gitee地址</span>
    },
    {
      key: '3',
      label: <span>github地址</span>
    },
    {
      key: 'logout',
      label: <div>退出登录</div>
    }
  ]
  const onMenuClick: MenuProps['onClick'] = ({ key }) => {
    if (key === 'logout') {
      logout().then(() => {
        navigate('/login')
      })
    }
  }

  const initTheme = () => {
    if (theme === 'dark') {
      document.documentElement.dataset.theme = 'dark'
      document.documentElement.classList.add('dark')
    }
  }

  const handleChangeTheme = () => {
    updateTheme()
    if (theme === 'dark') {
      document.documentElement.dataset.theme = 'light'
      document.documentElement.classList.remove('dark')
    } else {
      document.documentElement.dataset.theme = 'dark'
      document.documentElement.classList.add('dark')
    }
  }
  return (
    <div className={styles.navHeader}>
      {layout === 'top' ? (
        <TopBar />
      ) : (
        <div className={styles.left}>
          <Button
            className={styles.collapsed}
            type='text'
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => updateCollapsed()}
          />
          <BreadCrumb />
        </div>
      )}
      <div className={styles.right}>
        <div className={styles.right_item}>
          <Tooltip title='主题切换'>
            <img
              src={theme === 'light' ? SunnyIcon : MoonIcon}
              alt=''
              className={styles.themeIcon}
              onClick={handleChangeTheme}
            />
          </Tooltip>
        </div>
        <Dropdown menu={{ items: dropdownItems, onClick: onMenuClick }} placement='bottom' trigger={['click']}>
          <div className={styles.userInfo}>
            <img src={avaterIcon} className={styles.avater} />
            <span>{userInfo.userName}</span>
          </div>
        </Dropdown>
      </div>
    </div>
  )
}

export default NavHeader
